package cn.com.bluemoon.daps.system.auth;

import cn.com.bluemoon.daps.common.datascope.AuthRole;
import cn.com.bluemoon.daps.common.datascope.aop.AuthAccessService;
import cn.com.bluemoon.daps.common.domain.UserInfoHolder;
import cn.com.bluemoon.daps.common.exception.DapException;
import cn.com.bluemoon.daps.common.toolkit.BmAssetUtils;
import cn.com.bluemoon.daps.system.entity.DapSystemBizLine;
import cn.com.bluemoon.daps.system.service.DapSystemBizLineService;
import cn.hutool.extra.spring.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * 业务线-更新操作权限控制
 *
 * @author Jarod.Kong
 */
@Slf4j
public class BizLineUpdateAuthAccessService implements AuthAccessService {
    private final DapSystemBizLineService bizLineService;

    public BizLineUpdateAuthAccessService() {
        bizLineService = SpringUtil.getBean(DapSystemBizLineService.class);
        if (bizLineService == null) {
            log.warn("获取业务线服务bean失败！！");
        }
    }

    @Override
    public void checkAuth(UserInfoHolder.UserInfo userInfo,
                          AuthRole authRole,
                          boolean hasRoleAuth,
                          ProceedingJoinPoint aspectPoint,
                          HttpServletRequest servletRequest) throws DapException {
        if (bizLineService != null && userInfo.getAccount() != null) {
            if (hasRoleAuth) {
                log.info("用户{}拥有角色{}，放行", userInfo.getAccount(), Arrays.toString(authRole.roleAuth()));
                return;
            }
            Integer bizLineId = pjpArgCastTo(aspectPoint.getArgs()[1], Integer.class);
            DapSystemBizLine bizLine = bizLineService.getById(bizLineId);
            if (bizLine != null) {
                BmAssetUtils.isTrue(bizLine.getDataManager().equalsIgnoreCase(userInfo.getAccount()), authRole.errorMsg());
            }
        }
    }

}
